//load('apps/app/test/cucumber.js')

load('apps/app/test/selenium_config.js'); //load selenium config
load('jmvc/rhino/loader.js');
rhinoLoader(function(){
    include.setPath('apps/testing');
    include.plugins('test');
});


var browserStartCommand = SeleniumBrowsers[0];
var driver = new jQuery.Test.SeleniumDriver(browserStartCommand);
currentDriver = driver;

Givens = []

Given  = function(str, func){
        this.func = func;
        this.str = str;
        var regexp = this.str.replace(/\$\w+/g, "(?:([^\\s\"']+)|\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"|'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)')").replace(/\s+/g,"\\s+")
        this.regexp = new RegExp(regexp,"i");
        Givens.push(this)
    }
Given.prototype = {  
    check : function(line){
        return this.regexp.test(line)
    },
    run : function(str, next){
        var args = this.getArgs(str)
        var cur = this.str
        var done = function(){
            setTimeout(function(){
                new Statement(next).run()
            }, 1000)
        }
        done.timeout = 10000
        this.func.apply(driver, args.concat(done))
    },
    getArgs : function(str){
        var matches = this.regexp.exec(str)
        matches.shift();
        var args = [], tmp;
        while(matches.length){
            if( (tmp = matches.shift())) args.push(tmp)
        }
        return args;
    }
};


new Given("I am logged in as $user@$domain $pass",function(user,server, pass, done){
   this.type("#url",server).type("#username",user).type("#password",pass).click("input[type=submit]");
   var self= this;
   this.pathname("/ftp/client", function(){
       print("IT IS AT THE RIGHT PLACE")
       self.load();
       done()
   });
});
new Given("I $verb on $subject", function(verb, subject, done){
    print("verbinnn")
    this[verb](subject)
    done();
});
new Given("the page has loaded", function(done){
    this.loaded(done)
})

var f     = readFile("test/features/entries.feature"),
    lines = f.replace(/\r/,"").split('\n')

Statement = function(i){
    this.lineN = i;
}

Statement.prototype.run = function(){
    if(this.lineN >= lines.length){
        return print("\n\n DONE!");
    }
    print(this.lineN)
    print(lines[this.lineN])
    for(var g =0; g < Givens.length; g++){
        if(Givens[g].check(lines[this.lineN])){
            print("Got match")
            Givens[g].run(lines[this.lineN], this.lineN+1)
            found = true
        } 
    }
    if(!found) print("nothing found for line!\n"+lines[this.lineN])
};
new Statement(0).run();



